package com.example.wac.job.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.example.wac.job.StockJob;
import com.example.wac.job.listener.TaskJobListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author wuancheng
 * @description
 * @date 2022-01-05 11:15:00
 */

@Configuration
public class StockJobConfig {
    @Autowired
    ZookeeperRegistryCenter registryCenter;

    @Autowired
    StockJob stockJob;

    @Autowired
    TaskJobListener jobListener;

    /**
     * 配置任务调度: 参数:   任务
     *                    zk注册中心
     *                    任务详情
     * 创建bean容器前完成bean类中定义的初始化方法
     */
//    @Bean(initMethod = "init")
    public JobScheduler simpleJobScheduler(@Value("${SimpleJob.cron}") String cron,
                                           @Value("${SimpleJob.shardingTotalCount}") Integer shardingTotalCount,
                                           @Value("${SimpleJob.shardingItemParameters}") String shardingItemParameters) {
        return new SpringJobScheduler(stockJob, registryCenter,
                getSimpleJobConfiguration(
                        stockJob.getClass(),
                        cron,
                        shardingTotalCount,
                        shardingItemParameters),
                jobListener
        );
    }

    /**
     * 创建简单任务详细信息
     */
    public LiteJobConfiguration getSimpleJobConfiguration(final Class<? extends SimpleJob> jobClass, //任务类
                                                          final String cron,    // 运行周期配置
                                                          final int shardingTotalCount,  //分片个数
                                                          final String shardingItemParameters) {  // 分片参数
        return LiteJobConfiguration.newBuilder(new SimpleJobConfiguration(
                JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount)
                        .shardingItemParameters(shardingItemParameters)
                        .build(), jobClass.getCanonicalName()))
                .overwrite(true)
                .build();
    }

}
